﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Utils;
using LevenBlog.Core.Cache;

namespace LevenBlog.Core.Service {
    public static class Comment {
        public static int Count(IDbProvider provider, CommentState state) {
            int num = ProviderManager.Factory.Comment.Count(provider, state);
            return num;
        }

        public static int Count(IDbProvider provider, int blogid, CommentState state) {
            int num = ProviderManager.Factory.Comment.Count(provider, blogid, state);
            return num;
        }

        public static void Insert(IDbProvider provider, lb_comment comment) {
            provider.BeginTransaction();
            string mails = string.Empty;
            lb_blog blog;
            try {
                ProviderManager.Factory.Comment.Insert(provider, comment);
                blog = ProviderManager.Factory.Blog.Get(provider, comment.blogid);
                blog.commentnum++;
                if (comment.ismailnew && comment.userid > 0) {
                    if (string.IsNullOrEmpty(blog.mails))
                        blog.mails = comment.userid.ToString();
                    else if (blog.mails.IndexOf("|" + comment.userid + "|") < 0 &&
                        !blog.mails.StartsWith(comment.userid + "|") &&
                        !blog.mails.EndsWith("|" + comment.userid) &&
                        blog.mails.Trim() != comment.userid.ToString()) {
                        if (!blog.mails.EndsWith("|"))
                            blog.mails += "|";
                        blog.mails += comment.userid;
                    }
                }
                if (!comment.ismailnew && comment.userid > 0) {
                    if (!string.IsNullOrEmpty(blog.mails)) {
                        if (blog.mails.Trim() == comment.userid.ToString())
                            blog.mails = string.Empty;
                        else {
                            blog.mails = blog.mails.Replace("|" + comment.userid + "|", "|");
                            if (blog.mails.StartsWith(comment.userid.ToString() + "|"))
                                blog.mails = blog.mails.Substring(comment.userid.ToString().Length + 1);
                            if (blog.mails.EndsWith("|" + comment.userid))
                                blog.mails = blog.mails.Substring(0, blog.mails.Length - comment.userid.ToString().Length - 1);
                        }
                    }
                }
                mails = blog.mails;
                ProviderManager.Factory.Blog.Update(provider, blog);
                lb_state state = State.Get(provider);
                state.commentnum++;
                State.Update(provider, state);
                provider.Commit();
            } catch (Exception e) {
                provider.Rollback();
                throw new Exception("添加新的评论错误", e);
            }
            //下面开始发发邮件
            lb_config config = Config.Get(provider);
            if (config.issmtp) {
                List<int> idlist = new List<int>();
                string[] idarray = mails.Split('|');
                int temp = -1;
                foreach (string item in idarray) {
                    if (int.TryParse(item, out temp)) {
                        idlist.Add(temp);
                    }
                }
                MailSender sender = new MailSender();
                sender.SmtpHost = config.smtpserver;
                sender.SmtpUser = config.smtpuser;
                sender.SmtpPassword = config.smtppassword;
                sender.FromMail = config.smtpsender;
                IList<string> sendmails = ProviderManager.Factory.User.GetMail(provider, idlist.ToArray());
                foreach (string item in sendmails) {
                    if (item.Length > 0) {
                        try {
                            sender.ToMails.Add(item);
                        } catch {
                        }
                    }
                }
                MailEntity mail = new MailEntity();
                mail.Title = string.Format("{0}在日志{1}发布新评论.", comment.user, blog.title);
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("{0}在日志{1}发布新评论.<br /><br />", comment.user, blog.title);
                sb.AppendLine(comment.content);
                sb.AppendLine();
                sb.AppendLine("<br /><br />更多信息请参阅:<a href=\"" + config.url + "\" title=\"首页\">" + config.url + "</a>");
                mail.Content = sb.ToString();
                sender.Mail = mail;
                if (sender.ToMails.Count > 0) {
                    try {
                        sender.Send();
                    } catch {
                    }
                }
            }
            State.Remove();
        }

        public static void Update(IDbProvider provider, lb_comment comment) {
            ProviderManager.Factory.Comment.Update(provider, comment);
        }

        public static void Delete(IDbProvider provider, int id) {
            provider.BeginTransaction();
            try {
                lb_comment comment = ProviderManager.Factory.Comment.Get(provider, id);
                lb_blog blog = ProviderManager.Factory.Blog.Get(provider, comment.blogid);
                if (comment.ismailnew && comment.userid > 0) {
                    string temp = blog.mails.Replace("|" + comment.userid + "|", "|");
                    if (temp.StartsWith(comment.userid.ToString() + "|"))
                        temp = temp.Substring(comment.userid.ToString().Length + 1);
                    if (temp.EndsWith("|" + comment.userid))
                        temp = temp.Substring(0, temp.Length - comment.userid.ToString().Length - 1);
                    blog.mails = temp;
                }
                blog.commentnum--;
                ProviderManager.Factory.Blog.Update(provider, blog);
                lb_state state = State.Get(provider);
                state.commentnum--;
                State.Update(provider, state);
                ProviderManager.Factory.Comment.Delete(provider, id);
                provider.Commit();
            } catch (Exception e) {
                provider.Rollback();
                throw new Exception("无法删除该评论.", e);
            }
            State.Remove();
        }

        public static lb_comment Get(IDbProvider provider, int id) {
            return ProviderManager.Factory.Comment.Get(provider, id);
        }

        public static IList<lb_comment> Get(IDbProvider provider, int blogid, int pageSize, int currentPage, CommentState state) {
            return ProviderManager.Factory.Comment.GetFromBlogID(provider, blogid, pageSize, currentPage, state);
        }

        public static IList<lb_comment> Get(IDbProvider provider, int pagesize, int currentPage, CommentState state) {
            return ProviderManager.Factory.Comment.Get(provider, pagesize, currentPage, state);
        }
    }
}
